package cfengMiddleware.server.rabbitmq.consumer;

import CfengMiddleWare.model.entity.UserOrder;
import CfengMiddleWare.model.mapper.UserOrderMapper;
import cfengMiddleware.server.rabbitmq.entity.MessageEntity;
import cfengMiddleware.server.service.DeadUserOrderService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author Cfeng
 * @date 2022/9/18
 */

@RequiredArgsConstructor
@Component
@Slf4j
public class DeadConsumer {

    private final ObjectMapper objectMapper;

    private final UserOrderMapper userOrderMapper;

    private final DeadUserOrderService userOrderService;

    //这里就自动确认消费即可
    @RabbitListener(queues = "${spring.rabbitmq.queue-basic-name}",containerFactory = "singleListenerContainer")
    public void consumeMessage(@Payload MessageEntity messageEntity) {
        try {
            log.info("死信队列消息模型 消费者 监听到消息 ： {}", messageEntity);
            //业务逻辑，处理消息, orderID在messageEntity中, 本来可以编写更加精确的sql，但这里cfeng就直接使用生成的处理一下
            UserOrder userOrder = userOrderMapper.selectById(messageEntity.getId());
            if(!Objects.isNull(userOrder)) {
                if(Objects.equals(userOrder.getStatus(),1)) {
                    //未支付
                    userOrderService.updateUserOrderRecord(userOrder);
                }
            }
        } catch (Exception e) {
            log.info("死信队列消息模型 消费者 消费异常： {}",messageEntity,e.fillInStackTrace());
        }
    }
}
